package com.emapp.lccode.http

import android.util.Log
import com.emapp.lccode.bean.ApiResponse
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Converter
import java.io.IOException
import java.lang.reflect.Type

/**
 * @Description: TODO
 * @Author: zhang
 * @Date: 2023/8/17
 */
class CustomResponseConverter<T> internal constructor(
    private val gson: Gson,
    private val adapter: TypeAdapter<T>,
    private val mType: Type
) : Converter<ResponseBody, T> {
    override fun convert(value: ResponseBody): T {
        return try {
            val body = value.string()
            val json = JSONObject(body)
            val ret = json.optInt("code")
            val msg = json.optString("msg", "")
            if (ret == 0) {
                gson.fromJson(body, mType)
            } else {
                ApiResponse(ret, msg, null) as T
            }
        } catch (e: Exception) {
            throw RuntimeException(e.message)
        } finally {
            value.close()
        }
    }
}
